<?php
require_once(Mage::getBaseDir('lib')."/K3/k3.class.php");
class Silk_Mapi_Model_Api2_Shipping_Rest extends Silk_Mapi_Model_Api2_Shipping
{
    protected $page;
    protected $shippingId;
    protected $shippingOrderCollection;

    /**
     * 运单详情
     * @return array
     */
    public function _retrieve()
    {
        $results = $this->getShippingInformation();
        $results['orders'] = $this->getShippingOrders();

        return $results;
    }

    /**
     *开始配送
     * @return array
     */
    public function _multiUpdate()
    {
        $shippingId = $this->getParam('shipping_id');
        if (!$shippingId) {
            $this->_critical('缺少参数4！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        /** @var Silk_Tms_Model_Shipping $shipping */
        $shipping = Mage::getModel('tms/shipping')->load($shippingId);
        if (!$shipping || !$shipping->getId()) {
            $this->_critical('运单不存在！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        if ($shipping->getStatus() != Silk_Tms_Helper_Status::STATUS_SHIPPING_SORTED) {
            $this->_critical('运单还未分拣完成！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        /** @var Silk_Tms_Model_Mysql4_Shipping_Order_Collection $collection */
        $collection = Mage::getModel('tms/shipping_order')->getCollection()
            ->addFieldToFilter('shipping_id', array('eq' => $shippingId))
            ->addFieldToFilter('status', array('eq' => Silk_Tms_Helper_Status::STATUS_ORDER_NEW));
        if ($collection->getSize() > 0) {
            $this->_critical('运单中还有订单未取货！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }
        $shipping->setStatusDelivering();
        if (!$shipping->isLock()) {
            $shipping->setLock(1);
        }

        /** @var Mage_Core_Model_Resource_Transaction $transactionSave */
        $transactionSave = Mage::getModel('core/resource_transaction');
        $orders = $this->getShippingOrderCollection($shippingId);
        foreach ($orders as $order) {
            $order->setStatus(Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERING);

            $transactionSave->addObject($order);
        }
        $transactionSave->addObject($shipping);
			try {
            $transactionSave->save();
			} catch (Exception $e) {
				$this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
			}
        
        return array();
    }

    public function _retrieveCollection()
    {
        $results = array(
            'shippings' => array(),
            '_meta' => array(),
        );
        $shippingCollection = $this->getShippingCollection();
        $this->applyStatusFilter($shippingCollection);
        $this->applyExceptFilter($shippingCollection);
        $this->applyDateFilter($shippingCollection);

        $meta = $this->applyPageFilter($shippingCollection);
        if ($meta)
            $results['_meta'] = $meta;
        else
            return json_decode('{}');

        $results['shippings'] = $this->formatShippingCollection($shippingCollection);

        return $results;
    }

    protected function applyStatusFilter(Silk_Tms_Model_Mysql4_Shipping_Collection $collection)
    {
        $status = $this->getRequest()->getParam('status');
        if ($status) {
            $collection->addFieldToFilter('status', array('eq' => $status));
        }
    }

    protected function applyExceptFilter(Silk_Tms_Model_Mysql4_Shipping_Collection $collection)
    {
        $except = $this->getRequest()->getParam('except');
        if ($except) {
            $collection->addFieldToFilter('status', array('neq' => $except));
        }
    }

    protected function applyDateFilter(Silk_Tms_Model_Mysql4_Shipping_Collection $collection)
    {
        $begin = $this->getRequest()->getParam('time_begin');
        $end = $this->getRequest()->getParam('time_end');
        if ($begin) {
            $collection->addFieldToFilter('completed_at', array('from' => $this->formatDateTime($begin), 'datetime'=>true));
        }
        if ($end) {
            $collection->addFieldToFilter('completed_at', array('to' => $this->formatDateTime($end), 'datetime'=>true));
        }

        $collection->setOrder('completed_at', 'DESC');
    }

    protected function applyPageFilter(Silk_Tms_Model_Mysql4_Shipping_Collection $collection)
    {
        $this->page = abs($this->getRequest()->getParam('page')) ?: 1;
        $pageSize = abs($this->getRequest()->getParam('limit')) ?: 10;
        $count = $collection->getSize();
        $totalPages = ceil($count / $pageSize);
        $collection->setCurPage($this->page)->setPageSize($pageSize);

        if ($count && $this->page <= $totalPages) {
            return array(
                'totalItems' => $count,
                'totalPages' => $totalPages,
                'currentPage' => $this->page,
                'pageSize' => $pageSize
            );
        } else {
            return false;
        }
    }

    /**
     * @param Silk_Tms_Model_Mysql4_Shipping_Collection $collection
     * @return array
     */
    protected function formatShippingCollection(Silk_Tms_Model_Mysql4_Shipping_Collection $collection)
    {
        $result = array();
        $statusHelper = Mage::helper('tms/status');
        foreach ($collection as $item) {
            $shippingId = $item->getId();
            //add by wanglin start运单增加完成时间
            if($item->getCompletedAt()){
                $completetime = $this->convertDate($item->getCompletedAt());
            }else{
                $completetime = '';
            }
            //add by wanglin end

            $result[] = array(
                'id' => (int)$shippingId,
                'increment_id' => $item->getIncrementId(),
                'status' => $statusHelper->getStatus($item->getStatus(), 'shipping'),
                'status_code' => $item->getStatus(),
                'shipping_time' => $this->convertDate(date('Y-m-d H:i:s',strtotime($item->getCreatedAt())+8*3600)),
                'shipping_complete_time'=> $completetime,
                'order_new' => $this->getProcessingOrderCount($shippingId),
                'order_delivering' => $this->getDeliveringOrderCount($shippingId),
                'order_completed' => $this->getDeliveredOrderCount($shippingId),
                'order_refund' => $this->getRefundOrderCount($shippingId),
                'order_total' => $this->getOrderTotalCount($shippingId),
                'subtotal' => $this->formatPrice($item->getGrandTotal()),
                'grand_total' => $this->formatPrice($item->getTotalPaid()),
                'region' => $this->getRegionInfo($item->getRegionId()),
                'car' => $this->getCarInfo($item->getCarId()),
            );
        }

        return $result;
    }

    protected function getOrderTotalCount($shippingId)
    {
        $collection = $this->getShippingOrderCollection($shippingId)
            ->addFieldToFilter('status', array('neq' => Silk_Tms_Helper_Status::STATUS_ORDER_NEW));

        return (int)$collection->count();
    }

    protected function getProcessingOrderCount($shippingId)
    {
        $collection = $this->getShippingOrderCollection($shippingId)
            ->addFieldToFilter('status', array('eq' => Silk_Tms_Helper_Status::STATUS_ORDER_PROCESSING));

        return (int)$collection->count();
    }

    protected function getDeliveringOrderCount($shippingId)
    {
        $collection = $this->getShippingOrderCollection($shippingId)
            ->addFieldToFilter('status', array('eq' => Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERING));

        return (int)$collection->count();
    }

    protected function getDeliveredOrderCount($shippingId)
    {
        $collection = $this->getShippingOrderCollection($shippingId)
            ->addFieldToFilter('status', array('eq' => Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERED));

        return (int)$collection->count();
    }

    protected function getRefundOrderCount($shippingId)
    {
        $collection = $this->getShippingOrderCollection($shippingId)
            ->addFieldToFilter('status', array('eq' => Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERED))
            ->addFieldToFilter('total_refund', array('gt' => 0));

        return (int)$collection->count();
    }

    protected function getShippingOrders()
    {
        $collection = $this->getShippingOrderCollection();

        return $this->formatOrderCollection($collection);
    }

    /**
     * @param null $shippingId
     * @return Silk_Tms_Model_Mysql4_Shipping_Order_Collection
     */
    protected function getShippingOrderCollection($shippingId = null)
    {
        if ($shippingId == null)
            $shippingId = $this->getShippingId();

        /** @var Silk_Tms_Model_Mysql4_Shipping_Order_Collection $collection */
        $collection = Mage::getModel('tms/shipping_order')->getCollection()
            ->addFieldToFilter('shipping_id', array('eq' => $shippingId))
            ->setOrder("status='complete_order'", 'ASC')
            ->setOrder("status='delivered'", 'ASC');

        return $collection;
    }

    protected function getShippingInformation()
    {
        $shippingId = $this->getShippingId();

        /** @var Silk_Tms_Model_Shipping $item */
        $item = Mage::getModel('tms/shipping')->load($shippingId);
        if (!$item || !$item->getId()) {
            $this->_critical('运单不存在！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }

        return array(
            'subtotal' => $this->formatPrice($item->getGrandTotal()),
            'grand_total' => $this->formatPrice($item->getTotalPaid()),
            'not_receivables' => $this->formatPrice($item->getGrandTotal() - $item->getTotalPaid()),
            'region' => $this->getRegionInfo($item->getRegionId()),
            'car' => $this->getCarInfo($item->getCarId())
        );
    }

    protected function getCarInfo($carId)
    {
        if (!$carId) {
            return json_decode('{}');
        }

        $car = Mage::getModel('tms/car')->load($carId);
        if ($car && $car->getId()) {
            $labels = array("1" => "大", "2" => "中", "3" => "小");
            return array(
                'car_number' => $car->getNumber(),
                'car_type' => $labels[$car->getCarType()]
            );
        }

        return json_decode('{}');
    }

    protected function getRegionInfo($regionId)
    {
        if (!$regionId) {
            return '';
        }

        $region = Mage::getModel('tms/region')->load($regionId);
        if ($region && $region->getId()) {
            return $region->getName();
        }

        return '';
    }

    protected function formatOrderCollection(Silk_Tms_Model_Mysql4_Shipping_Order_Collection $collection)
    {
        $result = array();
        $statusHelper = Mage::helper('tms/status');
        foreach ($collection as $item) {
            if (!$customerId = $item->getCustomerId())
                $this->_critical('缺少参数5！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);

//add by wanglin start  查询订单状态
            $order = Mage::getModel('sales/order')->load($item->getOrderId());
            $order_status = $order->getStatus();
            if($order_status != "closed"){
            	$order_status = $item->getStatus();
            }
            $add_date = $order->getCreatedAt();
//add by wanglin end

            $storeInfo = $this->getStoreInfo($customerId);
            $result[] = array(
                'status' => $statusHelper->getStatus($order_status),
                'status_code' => $order_status,
                'store_name' => $storeInfo['name'],
                'order_id' => (int) $item->getOrderId(),
                'increment_id' => $item->getIncrementId(),
                'place_at' => $this->addEightHours($add_date),
                'address' => $storeInfo['address'],
                'address_description' => $storeInfo['addressDescription'] ?: '',
                'order_owner' => $item->getCustomerName(),
                'mobile' => $item->getCustomerPhone(),
                'subtotal' => $this->formatPrice($item->getGrandTotal()),
                'grand_total' => $this->formatPrice($item->getTotalPaid()),
                'longitude' => (float)$storeInfo['longitude'],
                'latitude' => (float)$storeInfo['latitude'],
                //'refund' => $item->getStatus() == Silk_Tms_Helper_Status::STATUS_ORDER_DELIVERED ? $this->getCreditmemoInfo($item->getOrderId()) : json_decode('{}')
				'refund'=>$this->getCreditmemoInfo($item->getOrderId()) ,
            );
        }
        return $result;
    }

    protected function getShippingId()
    {
        if (!$this->shippingId) {
            $shippingId = $this->getRequest()->getParam('id');
            if ($shippingId) {
                $this->shippingId = $shippingId;
            } else {
                $this->_critical('缺少参数6！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }
        }

        return $this->shippingId;
    }

    protected function getCreditmemoInfo($orderId)
    {
        $result = array();
        /** @var Mage_Sales_Model_Order_Creditmemo $creditmemo */
        $creditmemo = Mage::getModel('sales/order_creditmemo')->load($orderId, 'order_id');
        $comment = $creditmemo->getCommentsCollection()->getFirstItem()->getComment();
        if ($creditmemo && $creditmemo->getId()) {
            $result = array(
                'increment_id' => $creditmemo->getIncrementId(),
                'grand_total' => $this->formatPrice($creditmemo->getGrandTotal()),
                'comment_text' => $comment ?: ''
            );
        }

        return $result ?: json_decode('{}');
    }

}